package cn.how2j.basics.series.reflect;

import cn.how2j.basics.charactor.Hero;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by SilentJhin on 2020/8/23 14:06
 */
public class Test2Reflection {
    public static void main(String[] args) {
        String className = "cn.how2j.basics.charactor.Hero";
        try {
            Class pClass = Class.forName(className);
            Constructor c = pClass.getConstructor();
            Hero h2 = (Hero)c.newInstance();
            String fileContent = readFile();
            //System.out.println(fileContent);
            Class class3 = Class.forName(fileContent);
            Hero h3 = (Hero)class3.getConstructor().newInstance();
            //System.out.println(h2 instanceof Hero);
            //System.out.println(h3 instanceof Hero);
            //accessAttributes();
            callMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String readFile(){
        File file = new File("src\\cn\\how2j\\basics\\series\\reflect\\resources\\hero.config.txt");
        StringBuffer results = new StringBuffer();
        try (BufferedReader reader = new BufferedReader(new FileReader(file));){
            String tempStr;
            while (null != (tempStr = reader.readLine())){
                results.append(tempStr);
            }
            return results.toString();
        } catch (Exception e) {
            return "test";
        }
    }

    // 访问属性
    public static void accessAttributes(){
        try {
            // 先获取类对象
            Class asClass = Class.forName("cn.how2j.basics.charactor.Hero");
            // 获取引用对象
            Hero hero = (Hero) asClass.getConstructor().newInstance();
            // 获取类属性
            Field f1 = asClass.getDeclaredField("name");
            f1.set(hero, "jhix");
            System.out.println(hero.name);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 调用方法
    public static void callMethod() {
        Hero h = new Hero();
        try {
            Method m = h.getClass().getMethod("showName", String.class, int.class);
            m.invoke(h, "str", 9527);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}





